package socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室服务端
 */
public class Server {
    //该集合存放所有客户端的输出流用于广播消息
    private List<PrintWriter> allout = new ArrayList<>();
    private ServerSocket serverSocket;

    public Server() {
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端安连接成功");

                //启动一个线程处理与该客户的交互
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录该客户端的IP地址信息
        private String name = "客户端";

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
            System.out.println(host);
        }


        @Override
        public void run() {
            if ("176.6.11.177".equalsIgnoreCase(host)) {
                name = "张磊";
            } else if ("176.6.11.178".equalsIgnoreCase(host)) {
                name = "孔赟";
            } else if ("176.6.11.172".equalsIgnoreCase(host)) {
                name = "汪育";
            } else if ("176.6.11.179".equalsIgnoreCase(host)) {
                name = "朱佚奇";
            }else if ("127.0.0.1".equalsIgnoreCase(host)) {
                name = "顾晓露";
            }

            PrintWriter pw = null;
            try {
            /*
              通过Socket获取输入流可以读取来自远端计算机发送过来的消息
            */
                InputStream ips = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(ips, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

            /*
                通过Socket获取输入流用于给客户端发送消息
             */
                OutputStream ops = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(ops, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);
                //将该输出流存入共享集合allOut中
                synchronized (allout){
                    allout.add(pw);
                }
                System.out.println(name + "上线了，当前在线人数:" + allout.size());

            /*
              这里循环读取客户端发送过来消息这里可能出现下面的异常:
              java.net.SocketException: Connection reset
              这个错误是由于远端异常断开导致的(没有进行TCP的挥手断开操作)，该异常无法通过
              逻辑避免。
            */
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(name + "说:" + message);
                    //将消息回复给客户端
                    synchronized (allout) {
                        for (PrintWriter o : allout) {
                            o.println(name + "说:" + message);
    //                        o.println(name + "说:顾晓露最帅！！！");
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //处理客户端断开后的操作
                synchronized (allout){
                    allout.remove(pw);
                }
                System.out.println(name + "下线了，当前在线人数:" + allout.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
